package com.kyzh.core.pager.weal.community

import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.util.Base64
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.atools.util.setWidth
import com.gushenge.core.beans.CommunityPingLunBean
import com.gushenge.core.beans.FragCommunityBean
import com.kingja.loadsir.core.LoadService
import com.kyzh.core.MyApplication
import com.kyzh.core.R
import com.gushenge.core.base.activity.BaseActivity
import com.kyzh.core.databinding.ActCommunityDetailBinding
import com.kyzh.core.databinding.HeaderCommunityDetailBinding
import com.kyzh.core.databinding.ItemCircleImageBinding
import com.kyzh.core.dialog.showSendMessageDialog
import com.kyzh.core.pager.weal.community.adapter.PingLunAdapter
import com.kyzh.core.pager.weal.community.viewmodel.CommunityViewModel
import com.kyzh.core.utils.*
import com.kyzh.core.utils.ViewUtils.dp
import com.littlejerk.rvdivider.builder.XGridBuilder
import me.wcy.htmltext.HtmlImageLoader
import me.wcy.htmltext.HtmlText


class CommunityDetailActivity : BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Context,id:String,title:String) {
            val starter = Intent(context, CommunityDetailActivity::class.java)
                .putExtra("id",id)
                .putExtra("title",title)
            context.startActivity(starter)
        }
    }
    private val  vm by viewModels<CommunityViewModel>()
    private lateinit var db : ActCommunityDetailBinding
    private lateinit var header : HeaderCommunityDetailBinding
    private lateinit var adapter:PingLunAdapter
    private var id :String?= null
    private var mp   = 1
    private lateinit var loadsir: LoadService<Any>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db = DataBindingUtil.setContentView(this, R.layout.act_community_detail)
        adapter =  PingLunAdapter(vm)
        header = HeaderCommunityDetailBinding.inflate(layoutInflater)
        id = intent.getStringExtra("id")
        db.title.setText( intent.getStringExtra("title"))
        db.revPingLun.adapter = adapter
        adapter.setEmptyView(R.layout.empty)
        loadsir = loadServiceInit(db.root) {
            //点击重试时触发的操作
            loadsir.showLoading()
        }
        initView()
        getData()

    }

    private fun initView() {
        setPingLun()
        adapter.loadMoreModule.setOnLoadMoreListener {
            mp ++
            vm.getPingLunList(mp,id){
                adapter.addData(this.data)
                adapter.loadMoreModule.loadMoreComplete()
                if(mp>=this.maxP){
                    adapter.loadMoreModule.loadMoreEnd(true)
                }
            }
        }
    }

    fun getData(){
        mp = 1
        vm.getNewsDetail(id){
            loadsir.showSuccess()
            this?.apply {
                setContext(this)
            }
        }
        vm.getPingLunList(mp,id){
            adapter.setNewInstance(this.data)
        }


    }

    private fun setPingLun() {
        adapter.setOnItemChildClickListener{a,v,p->
            val data = a.data[p] as CommunityPingLunBean.Data
            when(v.id){
                R.id.tvZan ->{
                    v.isEnabled = false
                    vm.zan(1,data.id,data.uid){

                        if(this ==1){
                            kotlin.runCatching {
                                if(data.isGood){
                                    data.good = (data.good.toInt()-1).toString()
                                }else{
                                    data.good = (data.good.toInt()+1).toString()
                                }
                            }
                            data.isGood =!data.isGood

                            a.notifyItemChanged(p)
                            v.isEnabled = true
                        }
                    }
                }
                R.id.back ->{
                    showSendMessageDialog("回复@${data.petName}") {
                        vm.huifu("1",this,data.id,data.uid){

                        }
                    }
                }
            }
        }
    }

    //顶部内容
    fun setContext(data: FragCommunityBean.Data){
        db.apply {
            d = data
            tvMsg.setOnClickListener {
                showSendMessageDialog("说点什么吧 ^_^ ") {
                    vm.huifu("0",this,data.id,data.id){

                    }
                }
            }
            tvZan.setOnClickListener {
                tvZan.isEnabled = false
                vm.zan(0,data.id,data.uid){
                    kotlin.runCatching {
                        if(data.isGood){
                            data.good = (data.good.toInt()-1).toString()
                        }else{
                            data.good = (data.good.toInt()+1).toString()
                        }
                    }
                    data.isGood = !data.isGood
                    tvZan.isEnabled = true
                    d = data
                }
            }
            if(!data.video.isNullOrBlank()){
                frame.setVisibility(true)
                video.setVisibility(true)
                rev.setVisibility(false)
                if(data.image!=null  && data.image.isNotEmpty()){
                    video.setConfig(data.video,data.image[0],0)
                }else{
                    video.setConfig(data.video,"",0)
                }
            }else if(data.image!=null  && data.image.isNotEmpty() &&data.image.size>0 ){
                video.setVisibility(false)
                frame.setVisibility(true)
                rev.setVisibility(true)
                if( data.image.size==1){
                    rev.setWidth(208.dp)
                }else{
                    rev.setWidth(339.dp)
                }
                val gridLayoutManager = GridLayoutManager(this@CommunityDetailActivity, 6)
                val value = object : GridLayoutManager.SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {
                        return when (data.image.size) {
                            1 -> 6
                            2 -> 3
                            else -> 2
                        }
                    }
                }

                gridLayoutManager.spanSizeLookup =value
                if (rev.itemDecorationCount > 0) {
//                    val itemDecorationAt = rev.getItemDecorationAt(0)
//                    if (itemDecorationAt == null) {
//                        rev.addItemDecoration(ver!!.build())
//                    }
                } else {
                    val ver =
                        XGridBuilder(this@CommunityDetailActivity).setSpacing(3f)//这几个Spacing的优先级可看XGridBuilder说明
                            //这几个color和drawable的优先级可看XGridBuilder说明
                            .setColor(Color.BLUE)
                            //可设置颜色和drawable,drawable>color
                            .setHLineColor(Color.WHITE)
                            .setVLineColor(Color.WHITE)
                            //是否包括边界
                            .setIncludeEdge(false)
                            //竖直和水平分割线交叉处绘制的是竖直分割线颜色（交叉处属于竖直分割线）
                            .setVerticalIncludeEdge(true)
                    rev.addItemDecoration(ver!!.build())
                }
                rev.layoutManager = gridLayoutManager

                val gameDetailBannerAdapter = object :BaseQuickAdapter<String,BaseDataBindingHolder<ItemCircleImageBinding>>(R.layout.item_circle_image,data.image){
                    override fun convert(
                        holder: BaseDataBindingHolder<ItemCircleImageBinding>,
                        item: String
                    ) {
                        holder.dataBinding?.d = item
                    }
                }
                rev.adapter = gameDetailBannerAdapter
                gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                     reviewImages(data.image, position)
                }
            }else{
                video.setVisibility(false)
                rev.setVisibility(false)
                frame.setVisibility(false)
            }
            tvTag2.setVisibility(!data.video.isNullOrBlank())

            when {
                data.isBest=="1" -> {
                    tvTag1.setVisibility(true)
                    tvTag1.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FA8C08"))
                    tvTag1.text = "置顶"
                }
                data.isJiajing == "1" -> {
                    tvTag1.setVisibility(true)
                    tvTag1.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FF726A"))
                    tvTag1.text = "精华"
                }
                else -> {
                    tvTag1.setVisibility(false)
                }
            }
        }
        header.tvContent.movementMethod = LinkMovementMethod.getInstance()
        HtmlText.from(String(Base64.decode(data.content, Base64.NO_PADDING)))
            .setImageLoader(object : HtmlImageLoader {
                override fun loadImage(
                    url: String,
                    callback: HtmlImageLoader.Callback
                ) {
                    Glide.with(MyApplication.instance)
                        .asBitmap()
                        .load(url)
                        .into(object : CustomTarget<Bitmap>() {
                            override fun onLoadCleared(placeholder: Drawable?) {
                            }
                            override fun onResourceReady(
                                resource: Bitmap,
                                transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?
                            ) {
                                callback.onLoadComplete(resource)
                            }
                        })
                }
                override fun getDefaultDrawable():  Drawable? {
                    return getDrawable(R.drawable.logo_new)
                }
                override fun getErrorDrawable(): Drawable? {
                    return getDrawable(R.drawable.logo_new)
                }

                override fun getMaxWidth(): Int {
                    return 355.dp
                }

                override fun fitWidth(): Boolean {
                    return true
                }
            })
            .into( db.tvContent)
    }
}